/**
 * Created by caoshun on 2025/6/6.
 */

import Logo from '@/assets/images/logo.png';
import { LOCAL, SESSION } from '@/constants/publicConstant';
import { EyeInvisibleOutlined, EyeTwoTone, LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, notification } from 'antd';
import Cookies from 'js-cookie';
import { useCallback, useEffect, useState } from 'react';
import styles from './index.css';

const cname = Cookies.get('userId') || '';

export default function Login() {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  // 初始化表单数据
  useEffect(() => {
    form.setFieldsValue({
      userId: cname,
      password: '',
      remember: !!cname,
    });
  }, [form]);

  // 直接登录
  const handleLogin = useCallback(() => {
    form
      .validateFields()
      .then(async (values) => {
        setLoading(true);
        try {
          // 调用登录接口
          const loginResponse = await fetch('/api/anyics-front/user/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              userId: values.userId,
              password: values.password,
            }),
          });

          const loginResult = await loginResponse.json();

          if (loginResult.code === 200 && loginResult.data) {
            const { token, userId, roles, positions } = loginResult.data;

            // 存储 token 和用户信息
            sessionStorage.setItem(SESSION.token, token);

            // 调用获取权限接口
            const permissionResponse = await fetch('/api/anyics-front/user/select-role-position', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`,
              },
              body: JSON.stringify({
                userId: userId,
                roleId: roles[0]?.roleId,
                positionId: positions[0]?.positionId,
              }),
            });

            const permissionResult = await permissionResponse.json();

            if (permissionResult.code === 200 && permissionResult.data) {
              // 存储用户权限数据到 allPermissions
              const userPermission = {
                userId: userId,
                roles: roles,
                positions: positions,
                allPermissions: permissionResult.data.allPermissions,
              };
              localStorage.setItem(LOCAL.USER_PERMISSION, JSON.stringify(userPermission));
              localStorage.setItem('allPermissions', JSON.stringify(permissionResult.data.allPermissions));
            }

            // 记住我逻辑
            if (values.remember) {
              Cookies.set('userId', values.userId);
              Cookies.set('roleId', roles[0]?.roleId || '');
              Cookies.set('positionId', positions[0]?.positionId || '');
            } else {
              Cookies.remove('userId');
              Cookies.remove('roleId');
              Cookies.remove('positionId');
            }

            notification.success({ message: '登录成功！' });
            window.location.href = '/workBench/demo';
          } else {
            notification.error({ message: loginResult.errorMsg || '登录失败，请检查用户名和密码' });
          }
        } catch (error) {
          console.error('Login error:', error);
          notification.error({ message: '登录失败，请检查网络连接' });
        } finally {
          setLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
      });
  }, [form]);

  // 支持回车键
  const handleKeyPress = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        handleLogin();
      }
    },
    [handleLogin],
  );

  return (
    <div className={styles.login}>
      <div className={styles.loginWrapper}>
        <div className={styles.loginHeader}>
          <div className={styles.logo}>
            <img alt="logo" src={Logo} />
          </div>
          <h1>Any Front UI</h1>
          <p>欢迎使用组件库管理系统</p>
        </div>

        <div className={styles.loginContainer}>
          <div className={styles.loginCard}>
            <div className={styles.cardHeader}>
              <h2>Welcome Back</h2>
              <p>请输入您的用户名和密码</p>
            </div>

            <Form form={form} layout="vertical" className={styles.loginForm} onKeyDown={handleKeyPress}>
              <Form.Item
                name="userId"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { max: 30, message: '用户名不能超过30个字符' },
                ]}
              >
                <Input
                  size="large"
                  allowClear
                  placeholder="请输入用户名"
                  prefix={<UserOutlined className={styles.inputIcon} />}
                  className={styles.loginInput}
                  autoComplete="username"
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { max: 30, message: '密码不能超过30个字符' },
                  { min: 6, message: '密码至少6个字符' },
                ]}
              >
                <Input.Password
                  size="large"
                  placeholder="请输入密码"
                  prefix={<LockOutlined className={styles.inputIcon} />}
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                  className={styles.loginInput}
                  autoComplete="current-password"
                />
              </Form.Item>

              <Form.Item name="remember" valuePropName="checked">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <label style={{ color: '#666', fontSize: '14px' }}>
                    <input type="checkbox" style={{ marginRight: '8px' }} />
                    记住我
                  </label>
                </div>
              </Form.Item>

              <Button
                type="primary"
                size="large"
                loading={loading}
                onClick={handleLogin}
                className={styles.loginButton}
                block
              >
                {loading ? '登录中...' : '登录'}
              </Button>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
}
